package com.lanou3g.ptp.organize.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanou3g.ptp.entity.Clazz;
import com.lanou3g.ptp.organize.mapper.ClazzMapper;
import com.lanou3g.ptp.organize.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Value("${REDIS_CLAZZ_KEY_PREFIX}")
    private String REDIS_CLAZZ_KEY_PREFIX;
    @Value("${REDIS_CLAZZ_KEY_EXPIRE}")
    private Long REDIS_CLAZZ_KEY_EXPIRE;
    @Override
    public void addClazz(Clazz clazz) {
        clazz.setCreateTime(new Date());
        clazz.setUpdateTime(new Date());
        clazz.setStatus(0);
        clazzMapper.addMajor(clazz);
    }

    @Override
    public Clazz findById(Long id) {
        String redisKey = REDIS_CLAZZ_KEY_PREFIX + id;
        String sc = redisTemplate.opsForValue().get(redisKey);
        if (sc==null){
            Clazz clazz = clazzMapper.findById(id);
            String s = JSON.toJSONString(clazz);
            redisTemplate.opsForValue().set(redisKey,s,REDIS_CLAZZ_KEY_EXPIRE, TimeUnit.MINUTES);
            return clazz;
        }else {
            Clazz clazz = JSON.parseObject(sc, Clazz.class);
            redisTemplate.expire(redisKey,REDIS_CLAZZ_KEY_EXPIRE,TimeUnit.MINUTES);
            return clazz;
        }
    }

    @Override
    public List<Clazz> findByIds(Long[] ids) {
        List<Clazz> clazzes = clazzMapper.findByIds(ids);
        return clazzes;
    }

    @Override
    public Clazz findByName(String name) {
        Clazz clazz = clazzMapper.findByName(name);
        return clazz;
    }

    @Override
    public List<Clazz> findAll() {
        List<Clazz> clazzes = clazzMapper.findAll();
        return clazzes;
    }

    @Override
    public void updateById(Long id, Clazz clazz) {
        clazz.setUpdateTime(new Date());
        clazzMapper.updateById(id,clazz);
    }

    @Override
    public void deleteById(Long id) {
        clazzMapper.deleteById(id);
    }

    @Override
    public void deleteByIds(Long[] ids) {
        clazzMapper.deleteByIds(ids);
    }
}
